#include <iostream>

#include <iostream>
#include <sstream>
#include <cassert>
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/system/error_code.hpp>
#include "ServerApp.h"
#ifndef WIN32
#include <sys/resource.h>
#include <unistd.h>
#endif

void handler(boost::asio::io_service* pIO,
	boost::asio::signal_set* pSet,
	const boost::system::error_code& ec,
	int signal_number)
{
	if (ec.value() != boost::system::errc::success)
	{
		std::cerr << "error: " << ec.message() << std::endl;
		return;
	}
	std::cout << "signal [" << signal_number << "] received. quit? [y/n]: ";
	char c;
	std::cin >> c;
	if (c == 'y')
		pIO->stop();
	else
	{
		pSet->async_wait(boost::bind(handler, pIO, pSet, _1, _2));
		std::cout << "waiting for signal..." << std::endl;
	}
}

using namespace std;

int main(int argc, char *argv[])
{
#ifndef WIN32
	rlimit lmt;
	lmt.rlim_cur = lmt.rlim_max = RLIM_INFINITY;

	if (int err = setrlimit(RLIMIT_CORE, &lmt) != 0)
	{
		std::cout << "set RLIMIT_CORE limit error " << err << "!\n";
	}

	lmt.rlim_cur = lmt.rlim_max = 65535;

	if (int err = setrlimit(RLIMIT_NOFILE, &lmt) != 0)
	{
		std::cout << "set RLIMIT_NOFILE limit error " << err << "!\n";
	}
#endif
	boost::asio::io_service	io_run;
	boost::asio::signal_set signals(io_run);

	signals.add(SIGINT);
	signals.add(SIGTERM);
#ifndef WIN32
	signals.add(SIGQUIT);
	signals.add(SIGPIPE);
#endif
	signals.async_wait(boost::bind(handler, &io_run, &signals, _1, _2));

	GetServerApp().start("config.xml", &io_run);

	io_run.run();

	GetServerApp().stop();

	return 0;
}